//package com.plian.system.service.hr.management.impl;
//
//import com.alibaba.excel.EasyExcel;
//import com.alibaba.excel.ExcelWriter;
//import com.alibaba.excel.write.metadata.WriteSheet;
//import com.alibaba.excel.write.metadata.fill.FillConfig;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.dao.pm.property.PropertyBasicsDao;
//import com.plian.system.entity.hr.management.ManagementAppointment;
//import com.plian.system.mapper.hr.management.ManagementAppointMapper;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.mybatis.support.Query;
//import com.plian.system.service.hr.management.IManagementAppointmentService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.file.FileService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.hr.management.ManagementAppointmentVO;
//import com.plian.system.wrapper.hr.management.ManagementAppointWrapper;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.springframework.stereotype.Service;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.File;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.net.URLEncoder;
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * @author panqb
// * @version 1.0
// * @description: 经理层聘用 服务实现类
// * @date 2022/4/2 上午11:27
// */
//@Service
//@Slf4j
//@AllArgsConstructor
//public class ManagementAppointmentServiceImpl extends BaseServiceImpl<ManagementAppointMapper, ManagementAppointment> implements IManagementAppointmentService, BaseFlowService {
//
//    IFormCodeService formCodeService;
//
//    FormWorkflowService formWorkflowService;
//
//    ManagementAppointWrapper managementAppointWrapper;
//
//    PropertyBasicsDao propertyBasicsDao;
//
//    private FileService fileService;
//
//    private ManagementAppointMapper managementAppointMapper;
//
//    @Override
//    public Boolean submit(ManagementAppointment managementAppointment) {
//        return saveOrUpdate(managementAppointment);
//    }
//
//    @Override
//    public boolean saveOrUpdate(ManagementAppointment managementAppointment) {
//        try{
//            if(Optional.ofNullable(managementAppointment.getPropertyId()).isPresent()){
//                PageData pd=propertyBasicsDao.findbyid(managementAppointment.getPropertyId());
//                if(pd!=null){
//                    String affiliatedOrgFullName=pd.getString("affiliatedOrgFullName");
//                    String orgGradation=pd.getString("orgGradation");
//                    managementAppointment.setAffiliatedOrgFullName(affiliatedOrgFullName);
//                    managementAppointment.setOrgGradation(orgGradation);
//                }
//                if (managementAppointment.getId() == null){
//                    managementAppointment.setCode(formCodeService.getCode(FormTypeConstant.HR_MANAGEMENT_APPOINTMENT));
//                    managementAppointment.setFormType(String.valueOf(FormTypeConstant.HR_MANAGEMENT_APPOINTMENT));
//                }
//                boolean result= super.saveOrUpdate(managementAppointment);
//                List<HashMap> listDoc = managementAppointment.getList_doc();
//                fileService.edit(managementAppointment.getId().toString(),listDoc);
//                return result;
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return false;
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            ManagementAppointment managementAppointment = getById(id);
//            if (managementAppointment == null) {
//                return false;
//            } else if (managementAppointment.getStatus() != null &&
//                    (managementAppointment.getStatus() != FormStatusConstant.STASH && managementAppointment.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//        }
//        return super.deleteLogic(ids);
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        /**
//         * 设置审批人和审批时间
//         */
//        ManagementAppointment managementAppointment = getById(id);
//        Date now = DateUtil.now();
//        updateById(managementAppointment);
//
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState);
//    }
//
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     * @param id 主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            ManagementAppointment managementAppointment = getById(id);
//            managementAppointment.setStatus(updateStatus);
//            updateById(managementAppointment);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        QueryWrapper<ManagementAppointment> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("id", Func.toLongList(org.apache.commons.lang3.StringUtils.join(formIds, StringPool.COMMA)));
//        List<ManagementAppointment> managementAppointments = list(queryWrapper);
//        List<ManagementAppointmentVO> managementAppointmentVOS = managementAppointWrapper.entityToVO(managementAppointments);
//        List<PageData> pageDataList = new ArrayList<>();
//        try{
//            if (CollectionUtil.isNotEmpty(managementAppointmentVOS)){
//                for (ManagementAppointmentVO vo : managementAppointmentVOS){
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getOrgName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("formType", FormTypeConstant.HR_MANAGEMENT_APPOINTMENT);
//                    pd.put("orgName", vo.getOrgName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.HR_MANAGEMENT_APPOINTMENT);
//    }
//
//    /**
//     * 报表导出
//     * @param query
//     * @param response
//     */
//    @Override
//    public void exportExcel(Query query, HttpServletResponse response) {
//        try{
//            List<SearchEntity> entityList = query.getSearch();
//            QueryWrapper<ManagementAppointment> queryWrapper = SearchParamEntiy.getQueryWrapper(
//                    Condition.getQueryWrapper(new ManagementAppointment()), entityList
//            );
//            queryWrapper.eq("status","3");
//            List<ManagementAppointment> managementAppointmentList=this.list(queryWrapper);
//            List<ManagementAppointmentVO> managementAppointmentVOList=managementAppointWrapper.entityToVO(managementAppointmentList);
//            List<ManagementAppointmentVO> list=report(managementAppointmentVOList);
//            int index=0;
//            //合计小计的聘用期限为空
//            for(ManagementAppointmentVO m:list){
//                String formType=m.getFormType();
//                if(!"-1".equals(formType)){
//                    String startTime=m.getAppointmentStartTime();
//                    String endTime=m.getAppointmentEndTime();
//                    String startToEnd=startTime+"至"+endTime;
//                    m.setAppointStartToEnd(startToEnd);
//                }
//                index++;
//                m.setIndex(index);
//            }
//
//            String separator = File.separator;
//            String exlPath = separator + "exceldemo" + separator + "managementAppointment.xlsx";
//            InputStream inputStream = this.getClass().getResourceAsStream(exlPath);
//            String fileName = URLEncoder.encode("经理层聘用信息", "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//            // 设置响应头和客户端保存文件名
//            response.setCharacterEncoding("utf-8");
//            OutputStream outputStream = response.getOutputStream();// 取得输出流
//            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
//            WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
//
//            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//            excelWriter.fill(list, fillConfig, writeSheet);
//            excelWriter.finish();
//            inputStream.close();
//            outputStream.close();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
//
//    @Override
//    public List<ManagementAppointmentVO> report(List<ManagementAppointmentVO> list) {
//        list.forEach(record->{
//            String orderNumber=record.getOrderNumber();
//            String startTime=record.getAppointmentStartTime();
//            String endTime=record.getAppointmentEndTime();
//            String startToEnd=startTime+"至"+endTime;
//            record.setAppointStartToEnd(startToEnd);
//            if(StringUtil.isNoneBlank(orderNumber)){
//                record.setIntOrderNumber(Integer.parseInt(orderNumber));
//            }else{
//                record.setIntOrderNumber(999);
//            }
//        });
//        //给所有数据按照单位编码升序，人员编码升序
//        list = list.parallelStream().sorted(Comparator.comparing(ManagementAppointmentVO::getCompanyCode).thenComparing(ManagementAppointmentVO::getIntOrderNumber).thenComparing(ManagementAppointmentVO::getUpdateTime,Comparator.reverseOrder())).collect(Collectors.toList());
//        List<ManagementAppointmentVO> resultData = new ArrayList<>() ;
//        String companyNameSearchId = "";
//        int count = 0;
//        int sum = 0;
//        for(int i =0;i< list.size();i++){
//            if(!companyNameSearchId.equals(list.get(i).getAffiliatedOrgFullName())){
//                if(i>0){
//                    ManagementAppointmentVO Total = new ManagementAppointmentVO();
//                    Total.setFormType("-1");
//                    Total.setAffiliatedOrgFullName("小计：" + count);
//                    resultData.add(Total);
//                    sum+=count;
//                }
//                companyNameSearchId = list.get(i).getAffiliatedOrgFullName();
//                count = 1;
//            }else{
//                count++;
//            }
//            resultData.add(list.get(i));
//        }
//        sum+=count;
//        ManagementAppointmentVO LastTotal = new ManagementAppointmentVO();
//        LastTotal.setAffiliatedOrgFullName("小计：" + count);
//        LastTotal.setFormType("-1");
//        resultData.add(LastTotal);
//
//        ManagementAppointmentVO SumTotal = new ManagementAppointmentVO();
//        SumTotal.setAffiliatedOrgFullName("总计：" + sum);
//        SumTotal.setFormType("-1");
//        resultData.add(SumTotal);
//        return resultData;
//    }
//}
